<%@ include file="/WEB-INF/template/include.jsp" %>
<%@ taglib prefix="simplelabentry" uri="/WEB-INF/view/module/simplelabentry/resources/simplelabentry.tld" %>

<openmrs:htmlInclude file="/scripts/jquery/jquery-1.3.2.min.js" />

<script type="text/javascript">
    var $j = jQuery.noConflict();
</script>
<openmrs:htmlInclude file="/dwr/interface/LabPatientListItem.js" />
<openmrs:htmlInclude file="/dwr/interface/LabResultListItem.js" />
<openmrs:htmlInclude file="/dwr/interface/DWRPatientService.js" />
<openmrs:htmlInclude file="/dwr/interface/DWRSimpleLabEntryService.js" />
<openmrs:htmlInclude file="/dwr/util.js" />
<openmrs:htmlInclude file="/moduleResources/simplelabentry/simplelabentry.js" />
<openmrs:htmlInclude file="/scripts/dojoConfig.js" />
<openmrs:htmlInclude file="/scripts/dojo/dojo.js" />
<openmrs:htmlInclude file="/scripts/easyAjax.js" />
<openmrs:htmlInclude file="/scripts/calendar/calendar.js" />

<openmrs:globalProperty key="simplelabentry.patientIdentifierType" var="patientIdType" />
<openmrs:globalProperty key="simplelabentry.rescheduleperiod" defaultValue="7" var="reschedulePeriod"/>
<
<script type="text/javascript">
    var contextPath = "${pageContext.request.contextPath}";
        <c:if test="${model.allowAdd == 'true'}">
        dojo.require("dojo.widget.openmrs.PatientSearch");

    _selectedPatientId = null;
    _selectedOrderId = null;

    dojo.addOnLoad( function() {
        //searchWidget = dojo.widget.manager.getWidgetById("pSearch");

        dojo.event.topic.subscribe("pSearch/select",
        function(msg) {
            if (msg.objs[0].patientId) {
                var patient = msg.objs[0];
                DWRSimpleLabEntryService.getPatient(patient.patientId, function(labPatient) { loadPatient(labPatient) });
                clearPatientAndSearchFields(false);
                _selectedPatientId = patient.patientId;
                $j("#otherIdentifier").text($j("#patientIdentifier").val());
                showMatchedPatientSection();

            } else if (msg.objs[0].href)
                document.location = msg.objs[0].href;
        }
    );

        searchWidget.postCreate = function() {
            if (searchWidget.patientId != "") {
                searchWidget.selectPatient(searchWidget.patientId);
            }
            else if (searchWidget.searchPhrase) {
                DWRSimpleLabEntryService.findPatients(searchWidget.searchPhrase, searchWidget.simpleClosure(searchWidget, "doObjectsFound"));
            }
        };

        searchWidget.selectPatient = function(patientId) {
            DWRSimpleLabEntryService.getPatient(patientId, searchWidget.simpleClosure(searchWidget, "select"));
        };

        searchWidget.doFindObjects = function(text) {
            DWRSimpleLabEntryService.findPatients(text, searchWidget.simpleClosure(searchWidget, "doObjectsFound"));
            return false;
        };

        searchWidget.getCountyDistrict = function(p) { return p.countyDistrict == null ? searchWidget.noCell() : p.countyDistrict; };
        searchWidget.getCityVillage = function(p) { return p.cityVillage == null ? searchWidget.noCell() : p.cityVillage; };
        searchWidget.getNeighborhoodCell = function(p) { return p.neighborhoodCell == null ? searchWidget.noCell() : p.neighborhoodCell; };
        searchWidget.getProgramState = function(p) { return p.programState == null ? searchWidget.noCell() : p.programState; };
        searchWidget.getLastObs = function(p) { return p.lastObs == null ? searchWidget.noCell() : p.lastObs; };

        searchWidget.getAddress = function(p) {
            str = (p.countyDistrict == null ? "" : p.countyDistrict);
            str += (p.cityVillage == null ? "" : ((str == "" ? "" : ", ") + p.cityVillage));
            str += (p.neighborhoodCell == null ? "" : ((str == "" ? "" : ", ") + p.neighborhoodCell));
            str += (p.address1 == null ? "" : ((str == "" ? "" : ", ") + p.address1));
            return str == "" ? searchWidget.noCell() : str;
        };

        searchWidget.displayHeaderRow = function() {
            this.setHeaderCellContent(this.getHeaderCellContent());
            this.headerRow.style.display="";
        };

        searchWidget.getHeaderCellContent = function() {
            var arr = new Array();
            arr.push('');
            arr.push('<spring:message code="Patient.identifier" javaScriptEscape="true"/>');
            arr.push('<spring:message code="PersonName.givenName" javaScriptEscape="true"/>');
            arr.push('<spring:message code="PersonName.middleName" javaScriptEscape="true"/>');
            arr.push('<spring:message code="PersonName.familyName" javaScriptEscape="true"/>');
            arr.push('<spring:message code="Person.age" javaScriptEscape="true"/>');
            arr.push('<spring:message code="Person.gender" javaScriptEscape="true"/>');
            arr.push('Group');
            arr.push('Last CD4');
            arr.push('Address');
                <openmrs:forEachDisplayAttributeType personType="patient" displayType="listing" var="attrType">
                arr.push('<spring:message code="PersonAttributeType.${fn:replace(attrType.name, ' ', '')}" javaScriptEscape="true" text="${attrType.name}"/>');
                </openmrs:forEachDisplayAttributeType>
                return arr;
        };

        searchWidget.getCellFunctions = function() {
            var arr = new Array();
            arr.push(searchWidget.simpleClosure(searchWidget, "getNumber"));
            arr.push(searchWidget.simpleClosure(searchWidget, "getId"));
            arr.push(searchWidget.simpleClosure(searchWidget, "getGiven"));
            arr.push(searchWidget.simpleClosure(searchWidget, "getMiddle"));
            arr.push(searchWidget.simpleClosure(searchWidget, "getFamily"));
            arr.push(searchWidget.simpleClosure(searchWidget, "getAge"));
            arr.push(searchWidget.simpleClosure(searchWidget, "getGender"));
            arr.push(searchWidget.simpleClosure(searchWidget, "getProgramState"));
            arr.push(searchWidget.simpleClosure(searchWidget, "getLastObs"));
            arr.push(searchWidget.simpleClosure(searchWidget, "getAddress"));
                <openmrs:forEachDisplayAttributeType personType="patient" displayType="listing" var="attrType">
                arr.push(searchWidget.simpleClosure(searchWidget, "getAttribute", "${attrType.name}"));
                </openmrs:forEachDisplayAttributeType>
                return arr;
        };

        searchWidget.addPatientLink = '<a href="javascript:showCreatePatient();">Create New Patient</a>';
        searchWidget.inputNode.select();
        changeClassProperty("description", "display", "none");
    });
        </c:if>

        function showMatchedPatientSection() {
        $j("#matchedPatientSection").show();
        $j(".nameMatch").show();
    }

    function loadPatient(labPatient) {
        $('matchedIdentifier').innerHTML = labPatient.identifier + (labPatient.otherIdentifiers == '' ? '' : '<br/><small>(' + labPatient.otherIdentifiers + ')</small>');
        $('matchedName').innerHTML = labPatient.givenName + ' ' + labPatient.middleName+ ' '+  labPatient.familyName;
        $('matchedGender').innerHTML = labPatient.gender;
        $('matchedAge').innerHTML = labPatient.ageStr;
        $('matchedDistrict').innerHTML = labPatient.countyDistrict;
        $('matchedAddress1').innerHTML = labPatient.address1;
    }

    function clearPatientAndSearchFields(includeNameSearch) {
        _selectedPatientId = null;
        clearSearchFields(includeNameSearch);
    }

    function clearSearchFields(includeNameSearch) {
        $j("#otherIdentifier").text('');
        $j("#nameMatchSection").hide();
        $j("#matchedPatientSection").hide();
        $j(".idMatch").hide();
        $j(".nameMatch").hide();
        $j(".createdPatientMatch").hide();
        $j("#createPatientSection").hide();
        $j(".orderDetailSection").remove().removeClass("orderDetailSection");
        $j(".labResultSection").hide();
        $j(".existingOrderRow").show();
        _selectedOrderId = null;
        if (includeNameSearch) {
                <c:if test="${model.allowAdd == 'true'}">
                dojo.widget.manager.getWidgetById("pSearch").clearSearch();
                </c:if>
            }
        $j("div.resultDiv:visible",".labResultSection").each(
                function(){
                		$j(this).hide();
         		}
         );
    }

    function returnToSearch() {
        clearPatientAndSearchFields(false);
        $j("#nameMatchSection").show();
    }

    function clearFormFields() {
        $j(".orderField").val('');
        $j(".existingOrderRow").css("background-color","white");
        $j(".editOrderRow").hide();
        clearPatientAndSearchFields(true);
    }

    function showCreatePatient() {
        clearSearchFields(true);
        $j("#createPatientSection").show();
    }

    function findNewPatient() {
        clearPatientAndSearchFields(true);
        dojo.widget.manager.getWidgetById("pSearch").inputNode.select();
        dojo.widget.manager.getWidgetById("pSearch").inputNode.focus();
    }

    function enableDisableOrderFields() {
        // Start date and location are never editable
        $j(".orderDetailSection input[name='startDate']").attr("disabled","true").css("color","blue");

    }

    function showNewOrder() {
        $j("#newIdentifierAddSection").hide();
        $j(".orderDetailTemplate").clone().removeClass("orderDetailTemplate").appendTo($j("#newOrderSection")).addClass("orderDetailSection").show();

        $j(".orderDetailSection input[name='startDate']").val('${model.orderDateStr}');
        $j(".orderDetailSection select[name='location']").val('${model.orderLocation}');
        $j(".orderDetailSection select[name='concept']").val('${model.orderConcept}');
        enableDisableOrderFields();
        $j(".orderDetailSection :button[name='CreateOrderButton']").click( function() { createOrder(); } );
    }

    function editOrder(orderId) {
        clearFormFields();
        $j("#viewOrderRow"+orderId).css("background-color","yellow");
        $j("#editOrderRow"+orderId).show();
        $j(".orderDetailTemplate").clone().removeClass("orderDetailTemplate").appendTo($j("#editOrderRow"+orderId)).addClass("orderDetailSection").show();

        $j(".orderDetailSection .labResultTemplateCell").removeClass("labResultTemplateCell").addClass("labResultCell");
        $j(".orderDetailSection .labResultTemplateConcept").removeClass("labResultTemplateConcept").addClass("labResultConcept");
        $j(".orderDetailSection .labResultDetailTemplate").removeClass("labResultDetailTemplate").addClass("labResultDetail");
        $j(".labResultSection").show();

        DWRSimpleLabEntryService.getOrder(orderId, function(order) {
            _selectedPatientId = order.patientId;
            _selectedOrderId = orderId;
            $j(".orderDetailSection input[name='startDate']").val(order.startDateString);
            enableDisableOrderFields();
            $j(".rescheduleTestSection").hide();
            $j(".labResultDetail input[name='discontinuedDate']").val(order.discontinuedDateString);

            for (i=0; i<order.labResults.length; i++) {
                $j("[name='resultValue."+order.conceptId+"."+order.labResults[i].conceptId+"']").val(order.labResults[i].result);
                $j("[name='didTestFail_"+order.conceptId+"."+order.labResults[i].conceptId+"']").val(order.labResults[i].testFailureCode);
                if(order.labResults[i].testFailureCode==1)
                {
                    $j(".labResultDetail").hide();
                    $j(".labFailureDetailTemplate").show();
                }
            }
            $j("#labResultSection"+order.conceptId).show();
        });
        $j(".orderDetailSection :button[name='CreateOrderButton']").click( function() { createOrder(); } );
    }

    function rescheduleOrder(orderId) {
        clearFormFields();
        $j("#viewOrderRow"+orderId).css("background-color","yellow");
        $j("#editOrderRow"+orderId).show();
        $j(".orderDetailTemplate").clone().removeClass("orderDetailTemplate").appendTo($j("#editOrderRow"+orderId)).addClass("orderDetailSection").show();

        $j(".orderDetailSection .labResultTemplateCell").removeClass("labResultTemplateCell").addClass("labResultCell");
        $j(".orderDetailSection .labResultTemplateConcept").removeClass("labResultTemplateConcept").addClass("labResultConcept");
        $j(".orderDetailSection .labResultDetailTemplate").removeClass("labResultDetailTemplate").addClass("labResultDetail");

        DWRSimpleLabEntryService.getOrder(orderId, function(order) {
            _selectedPatientId = order.patientId;
            _selectedOrderId = orderId;
            $j(".orderDetailSection input[name='startDate']").val(order.startDateString);
            enableDisableOrderFields();
            $j(".rescheduleTestSection").show();
            $j(".labResultDetail input[name='discontinuedDate']").val(order.discontinuedDateString);
        });
        $j(".orderDetailSection :button[name='CreateOrderButton']").click( function() { createOrder(); } );
    }


    function matchPatientById(patIdType, patId) {
        clearPatientAndSearchFields(false);
        //alert("patIdType = "+patIdType+ " patId = "+patId);
        DWRSimpleLabEntryService.getPatientByIdentifier(patIdType, patId, function(patient) {
            if (patient.patientId == null) {
                DWRSimpleLabEntryService.checkPatientIdentifier(patIdType, patId, {
                    callback:function(createdOrder) {
                        $j("#nameMatchSection").show();
                        //$('newPatientIdentifier').innerHTML = patId;
                    },
                    errorHandler:function(errorString, exception) {
                        alert(errorString);
                    }
                });
            }
            else {
                _selectedPatientId = patient.patientId;
                loadPatient(patient);
                $j(".idMatch").show();
                $j("#matchedPatientSection").show();
                $j("#newOrderSection").show();
                showNewOrder();
                //$('newPatientIdentifier').innerHTML = patId;
                for (var i = 0; i < patient.labOrderIdsForPatient.length; i++){
                    var optionVal = patient.labOrderIdsForPatient[i];
                    $j(".orderDetailSection select[name='previousAccessionNumber']").append(new Option(optionVal, optionVal));
                }

            }
        });
    }

    function createOrder() {
        saveOrder(null);
    }

    function saveOrder(orderId) {

        var orderLoc = 1;
        var orderDate = $j(".orderDetailSection input[name='startDate']").val();
        var todayDate = $j(".orderDetailSection input[name='today']").val();
        var accessionNum = $j(".orderDetailSection input[name='accessionNumber']").val();
        var previousAccessionNum = $j(".orderDetailSection select[name='previousAccessionNumber']").val();
        var discontinuedDate = $j(".labResultDetail input[name='discontinuedDate']").val();
        var rescheduleDate = $j(".orderDetailSection input[name='rescheduleDate']").val();
        if(rescheduleDate==null || rescheduleDate=="")
        {
            rescheduleDate = $j(".labFailureDetailTemplate input[name='rescheduleDate']").val();

        }
        var orderConceptIds = [];

        var index = 0;
            <c:if test="${model.confidentialTest!='true'}">
            <c:forEach items="${model.labTestConcepts}" var="labConcept" varStatus="labConceptStatus">
            var orderConcept = $j(".orderDetailSection input[name='${empty labConcept.name.shortName ? labConcept.name.name : labConcept.name.shortName}']:checked").val();
        if(orderConcept != null && orderConcept != '') {
            orderConceptIds[index++] = orderConcept;
        }
            </c:forEach>
            </c:if>

            <c:if test="${model.confidentialTest=='true'}">
            <c:forEach items="${model.confidentialTestConcepts}" var="labConcept" varStatus="labConceptStatus">
            var orderConcept = $j(".orderDetailSection input[name='${empty labConcept.name.shortName ? labConcept.name.name : labConcept.name.shortName}']:checked").val();
        if(orderConcept != null && orderConcept != '') {
            orderConceptIds[index++] = orderConcept;
        }
            </c:forEach>
            </c:if>

            var labResultMap = {};
        var blankResultMap = {};
        $j(".labResultConcept","div.resultDiv:visible").each( function(i) {
            var cIdsToSplit = $j(this).text();
            var cId = cIdsToSplit.split(".",2)[1];
            var resultStr = $j("[name='resultValue."+cIdsToSplit + "']").val();
			if(rescheduleDate==null || rescheduleDate=="")
			{
				if (resultStr != null && resultStr != '') {
					var r = new Object();
					r.conceptId = cId;
					r.result = resultStr;
					labResultMap[cId] = r;
				}
				else{
					$j("[name='resultValue."+cIdsToSplit + "']").css("background-color","blue");
					blankResultMap[cId] = cIdsToSplit;
				}
			}
			else
			{
				blankResultMap[cId] = cIdsToSplit;
			}
        });

        var allLabResultMap = {};
        $j(".labResultConcept","div.resultDiv:visible").each( function(i) {
            var cIdsToSplit = $j(this).text();
            var cId = cIdsToSplit.split(".",2)[1];
            var resultStr = $j("[name='resultValue."+cIdsToSplit + "']").val();
            if (resultStr != null && resultStr != '') {
            }
            var r = new Object();
            r.conceptId = cId;
            r.result = resultStr;
            allLabResultMap[cId] = r;
        });
		
		formatMonth()
		
		DWRSimpleLabEntryService.saveLabOrders(_selectedOrderId, _selectedPatientId, orderConceptIds, orderLoc, orderDate,rescheduleDate, discontinuedDate, labResultMap,allLabResultMap, function(){
			window.location.href = window.location.href; 		
		});
    }

    function deleteOrder(orderId, reason) {
        if (confirm("Are you sure you want to delete this order?")) {
            DWRSimpleLabEntryService.deleteLabOrderAndEncounter(orderId, reason, {
                callback:function() {location.reload();},
                errorHandler:function(errorString, exception) { alert(errorString); location.reload(); }
            });
        }
    }

    function showPrint(patientName,patientId,gender,age,testName,testDate){
        var content='Name: '+patientName+ ' <br/>Patient Id: '+patientId+' <br/>Test: '+testName +' <br/>Test Date: ' +testDate;
        if(!datelessthanequaltoday(testDate))
        {
            alert('You cant print label for future date.');
        }
        else
        {
                <c:forEach items="${model.confidentialTestConcepts}" var="labConcept" varStatus="labConceptStatus">
                if('${empty labConcept.name.shortName ? labConcept.name.name : labConcept.name.shortName}' == testName)
            {
                var content='Patient Id: '+patientId+' <br/>Age: '+age +' <br/>Sex: ' +gender;
            }
                </c:forEach>

                //alert(content);
            var pwin=window.open('Print Label','print_content','width=300,height=100');
            pwin.document.open();
            pwin.document.write('<html><body onload="window.print()">'+content+'</body></html>');
            pwin.document.close();
            setTimeout(function(){ pwin.close(); },1000);
        }

    }

	// ABC
    function scheduleOrder(failureId)
    {
        if(failureId == 1)
        {
            $j(".labResultDetail").hide();
            $j(".labFailureDetailTemplate").show();
            var rescheduleDate = new Date() ;
            var rescheduleDay = parseInt('${reschedulePeriod}');
            rescheduleDate.setDate(rescheduleDate.getDate() +  rescheduleDay) ;
            var date = rescheduleDate.getDate() + "/" +  formatMonth(rescheduleDate.getMonth() + 1)  + "/" + rescheduleDate.getFullYear(); 
            $j("input[name='rescheduleDate']", ".labFailureDetailTemplate").val(date);
        }
        else
        {
            $j(".labFailureDetailTemplate").hide();
            $j(".labResultDetail").show();
        }
    }
	
	function formatMonth(month){
		if(month<10){
			month = "0" + month;
		}
		return month;
	}
	
	

    function disableResultField()
    {
        if($j(".orderDetailSection input[name='rescheduledDate']").val().trim()!="" && $j(".orderDetailSection input[name='rescheduledDate']").val().trim()!="undefined")
        {
            $j(".labResultSection").hide();
        }
        else if($j(".orderDetailSection input[name='rescheduledDate']").val().trim()=="")
        {
            $j(".labResultSection").show();
        }
    }
    function datelessthanequaltoday(value) {
        var choseDate = getDateFromFormat(value, "dd/MM/yyyy");
        return value ? choseDate <= new Date() : true;
    }

    // Support method for date
    //Parse a string and convert it to a Date object.
    //If string cannot be parsed, return null.
    //Avoids regular expressions to be more portable.
    function getDateFromFormat(val, format) {
        val = val + "";
        format = format + "";
        var i_val = 0;
        var i_format = 0;
        var c = "";
        var token = "";
        var token2 = "";
        var x, y;
        var year = new Date().getFullYear();
        var month = 1;
        var date = 1;
        var hh = 0;
        var mm = 0;
        var ss = 0;
        var ampm = "";
        while (i_format < format.length) {
            // Get next token from format string
            c = format.charAt(i_format);
            token = "";
            while ((format.charAt(i_format) == c) && (i_format < format.length)) {
                token += format.charAt(i_format++);
            }
            // Extract contents of value based on format token
            if (token == "yyyy" || token == "yy" || token == "y") {
                if (token == "yyyy") {
                    x = 4;
                    y = 4;
                }
                if (token == "yy") {
                    x = 2;
                    y = 2;
                }
                if (token == "y") {
                    x = 2;
                    y = 4;
                }
                year = getInt(val, i_val, x, y);
                if (year == null) {
                    return null;
                }
                i_val += year.length;
                if (year.length == 2) {
                    if (year > 70) {
                        year = 1900 + (year - 0);
                    } else {
                        year = 2000 + (year - 0);
                    }
                }
            } else if (token == "MMM" || token == "NNN") {
                month = 0;
                var names = (token == "MMM" ? (Date.monthNames
                .concat(Date.monthAbbreviations)) : Date.monthAbbreviations);
                for ( var i = 0; i < names.length; i++) {
                    var month_name = names[i];
                    if (val.substring(i_val, i_val + month_name.length)
                    .toLowerCase() == month_name.toLowerCase()) {
                        month = (i % 12) + 1;
                        i_val += month_name.length;
                        break;
                    }
                }
                if ((month < 1) || (month > 12)) {
                    return null;
                }
            } else if (token == "EE" || token == "E") {
                var names = (token == "EE" ? Date.dayNames : Date.dayAbbreviations);
                for ( var i = 0; i < names.length; i++) {
                    var day_name = names[i];
                    if (val.substring(i_val, i_val + day_name.length).toLowerCase() == day_name
                    .toLowerCase()) {
                        i_val += day_name.length;
                        break;
                    }
                }
            } else if (token == "MM" || token == "M") {
                month = getInt(val, i_val, token.length, 2);
                if (month == null || (month < 1) || (month > 12)) {
                    return null;
                }
                i_val += month.length;
            } else if (token == "dd" || token == "d") {
                date = getInt(val, i_val, token.length, 2);
                if (date == null || (date < 1) || (date > 31)) {
                    return null;
                }
                i_val += date.length;
            } else if (token == "hh" || token == "h") {
                hh = getInt(val, i_val, token.length, 2);
                if (hh == null || (hh < 1) || (hh > 12)) {
                    return null;
                }
                i_val += hh.length;
            } else if (token == "HH" || token == "H") {
                hh = getInt(val, i_val, token.length, 2);
                if (hh == null || (hh < 0) || (hh > 23)) {
                    return null;
                }
                i_val += hh.length;
            } else if (token == "KK" || token == "K") {
                hh = getInt(val, i_val, token.length, 2);
                if (hh == null || (hh < 0) || (hh > 11)) {
                    return null;
                }
                i_val += hh.length;
                hh++;
            } else if (token == "kk" || token == "k") {
                hh = getInt(val, i_val, token.length, 2);
                if (hh == null || (hh < 1) || (hh > 24)) {
                    return null;
                }
                i_val += hh.length;
                hh--;
            } else if (token == "mm" || token == "m") {
                mm = getInt(val, i_val, token.length, 2);
                if (mm == null || (mm < 0) || (mm > 59)) {
                    return null;
                }
                i_val += mm.length;
            } else if (token == "ss" || token == "s") {
                ss = getInt(val, i_val, token.length, 2);
                if (ss == null || (ss < 0) || (ss > 59)) {
                    return null;
                }
                i_val += ss.length;
            } else if (token == "a") {
                if (val.substring(i_val, i_val + 2).toLowerCase() == "am") {
                    ampm = "AM";
                } else if (val.substring(i_val, i_val + 2).toLowerCase() == "pm") {
                    ampm = "PM";
                } else {
                    return null;
                }
                i_val += 2;
            } else {
                if (val.substring(i_val, i_val + token.length) != token) {
                    return null;
                } else {
                    i_val += token.length;
                }
            }
        }
        // If there are any trailing characters left in the value, it doesn't match
        if (i_val != val.length) {
            return null;
        }
        // Is date valid for month?
        if (month == 2) {
            // Check for leap year
            if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { // leap
                // year
                if (date > 29) {
                    return null;
                }
            } else {
                if (date > 28) {
                    return null;
                }
            }
        }
        if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
            if (date > 30) {
                return null;
            }
        }
        // Correct hours value
        if (hh < 12 && ampm == "PM") {
            hh = hh - 0 + 12;
        } else if (hh > 11 && ampm == "AM") {
            hh -= 12;
        }
        return new Date(year, month - 1, date, hh, mm, ss);
    }

    function getInt(str,i,minlength,maxlength) {
        for (var x=maxlength; x>=minlength; x--) {
            var token=str.substring(i,i+x);
            if (token.length < minlength) {
                return null;
            }
            if (_isInteger(token)) {
                return token;
            }
        }
        return null;
    }

    function _isInteger(val) {
        var digits="1234567890";
        for (var i=0; i < val.length; i++) {
            if (digits.indexOf(val.charAt(i))==-1) {
                return false;
            }
        }
        return true;
    }
    $j(document).ready(function(){
        changeBcg();
        if(${model.confidentialTest=='true'})
        {
            if($j("input[name='identifier']").val().trim()!="")
            {
                matchPatientById('${patientIdType}',$('patientIdentifier').value);
            }
        }

        $j("#AddIdentifierButton").click( function() {
            var ident = $j("#otherIdentifier").text();
            var identType = '${patientIdType}';
            var identLoc = '${model.orderLocation}';
            DWRSimpleLabEntryService.addPatientIdentifier(_selectedPatientId, ident, identType, identLoc,
            { 	callback:function(revisedPatient) {
                    loadPatient(revisedPatient);
                    showNewOrder();
                },
                errorHandler:function(errorString, exception) {
                    alert(errorString);
                }
            }
        );
        });
    });

    function acceptOrder(orderId, accept){
        $j("#acceptMsg"+orderId).hide();
        if(accept)
        {
            $j("#viewOrderRow"+orderId).css("background-color","#BAEC5B");
        }
        else
        {
            $j("#viewOrderRow"+orderId).css("background-color","white");
        }
        $j.ajax({
            type: "POST",
            url: contextPath+"/moduleServlet/simplelabentry/AcceptLabOrderServlet",
            data: "orderId="+orderId+"&accept="+accept,
            success: function(msg){
                $j("#acceptMsg"+orderId).attr('src',contextPath+'/images/'+msg).show('slow');
            }
        });
    }


    	function changeBcg(){
        $j(".acceptMsg").each(function(){
            if(jQuery(this).attr("checked")){
                $j("#viewOrderRow"+orderId).css("background-color","#BAEC5B");

            }

        });

}
</script>

<script type="text/javascript">

	/*
		Validate the form using Accepted Date, Current Date, Result Date
		Accepted Date <= Result Date <= Current Date
		If failed to validate, the Save button will be disable.
	*/
	function validateResultForm(input){
		resultDate = input.value;
		jQuery('#discontinuedDate').val(resultDate);
		currentDate = "${todayStr}";				
		acceptedDate = jQuery('#acceptedDate').val();
		
		if((acceptedDate<=resultDate) && (resultDate<=currentDate)){			
			jQuery("#discontinuedDateError").html("");
			jQuery("#saveOrderButton").attr('disabled', '');
		} else {
			jQuery("#discontinuedDateError").html("Invalid report date!");
			jQuery("#saveOrderButton").attr('disabled', 'disabled');			
		}
	}
	
	/*
		Save the order filled with result.
		Also update the discontinuedDate in case user use the default report date.
	*/
	function saveThisOrder(input){
		resultDate = jQuery('#fakeDiscontinuedDate').val();
		jQuery('#discontinuedDate').val(resultDate);
		saveOrder();		
	}
</script>

<style>
    th,td {text-align:left; padding-left:10px; padding-right:10px;}
    .searchSection {padding:5px; border: 1px solid grey; background-color: whitesmoke;}
    .labResultCell {white-space:nowrap;}
</style>

<b class="boxHeader">Step 2.  Manage orders / results</b>
<div style="align:left;" class="box" >

    <c:if test="${model.confidentialTest!='true'}">
        <div>
            <b>
                <c:choose>
                    <c:when test="${model.limit=='open'}">Open Orders</c:when>
                    <c:when test="${model.limit=='closed'}">Closed Orders</c:when>
                    <c:otherwise>All Orders</c:otherwise>
                </c:choose>
            </b>
            <table style="width:100%;">
                <tr style="background-color:#CCCCCC;">
                    <th>Sr. No.</th>
                    <th>Sample No.</th>
                    <c:if test="${model.workList != null && model.workList == 'true'  && model.futureDate == 'false'}">
                    <th>Results</th>
                    </c:if>
                    <th>Date</th>
                    <th>Patient ID</th>
                    <th>Name</th>
                    <th>Sex</th>
                    <th>Age</th>
                    <th>Test</th>
                </tr>
                <c:if test="${fn:length(model.labOrders) == 0}"><tr><td>No Orders</td></tr></c:if>
                <c:forEach items="${model.labOrders}" var="order" varStatus="orderStatus">
                    <c:if test="${!empty order.orderId}">
                        <tr id="viewOrderRow${order.orderId}" class="existingOrderRow">

                            <td>
                                ${orderStatus.count}
                            </td>
                            <td>${model.mapLabTest[order.orderId] }</td>
                        <c:if test="${model.workList != null && model.workList == 'true' && model.futureDate == 'false'}">
                            <td>
                            <a href="javascript:editOrder('${order.orderId}');"><small>Enter Results</small></a>
                            </td>
                        </c:if>
                        

                        <td><openmrs:formatDate date="${order.startDate}" /></td>

                        <td>${order.patient.patientIdentifier}</td>
                        <td>
                            
                                ${order.patient.personName.givenName} ${order.patient.personName.middleName} ${order.patient.personName.familyName}
                               </td>
                        <td>${order.patient.gender}</td>
                        <td>${order.patient.age}</td>
                        <td>${empty order.concept.name.shortName ? order.concept.name.name : order.concept.name.shortName}</td>
                        <!--<c:choose>
                                <c:when test="${labConcept.set}">
                                    <openmrs:forEachRecord name="conceptSet" conceptSet="${labConcept.conceptId}">
                                        <td>${ record.name.name }</td>
                                    </openmrs:forEachRecord>
                                </c:when>
                                <c:otherwise>
                                    <td>${labConcept.name.name}</td>
                                </c:otherwise>
                            </c:choose>-->
                        </tr>
                        <tr><td colspan="12" class="editOrderRow" style="display:none; background-color:#CCCCCC; border:2px solid blue;" id="editOrderRow${order.orderId}"></td></tr>

                    </c:if>
                </c:forEach>
            </table>
        </div>
    </c:if>

    <div class="orderDetailTemplate" style="display:none;">
        <b>Order Details</b>
        <input type="hidden" name="orderId" value="" />
        <table>
            <tr>
                <th><spring:message code="simplelabentry.orderDate" />: </th>
            <td><input type="text" id="acceptedDate" name="startDate" size="10" readonly="readonly"/></td> <!-- onFocus="showCalendar(this)"  -->
            </tr>
            <tr>
            <c:if test="${model.confidentialTest=='true'}">
                <c:forEach items="${model.confidentialTestConcepts}" var="labConcept" varStatus="labConceptStatus">
                    <input type="checkbox" value="${labConcept.conceptId}" name="${empty labConcept.name.shortName ? labConcept.name.name : labConcept.name.shortName}" id="${empty labConcept.name.shortName ? labConcept.name.name : labConcept.name.shortName}">
                  	  ${empty labConcept.name.shortName ? labConcept.name.name : labConcept.name.shortName}
                    </input>
                </c:forEach>
            </c:if>
            </tr>
        </table>
        <div class="rescheduleTestSection" style="display:none;">
            Reschedule Date:
            <input type="text" name="rescheduleDate" size="10" onFocus="showCalendar(this)"/>
        </div>
        <input type="hidden" name="orderConcept" value="" />
        <br/>
        <div class="labResultSection" style="display:none;">
            <b style="padding-bottom:10px;">Results</b>
            <c:forEach items="${model.labTestConcepts}" var="labConcept" varStatus="labConceptStatus">
                    <div class="resultDiv" id="labResultSection${labConcept.conceptId}" style="display:none;">
                        <table border="1px solid">
                            <tr>
                            <c:choose>
                                <c:when test="${labConcept.set}">
                                    <openmrs:forEachRecord name="conceptSet" conceptSet="${labConcept.conceptId}">
                                        <th>${ record.name.name }</th>
                                    </openmrs:forEachRecord>
                                </c:when>
                                <c:otherwise>
                                    ${labConcept.name.name}
                                </c:otherwise>
                            </c:choose>
                            </tr>

                            <tr>
                            <c:choose>
                                <c:when test="${labConcept.set}">
                                    <openmrs:forEachRecord name="conceptSet" conceptSet="${labConcept.conceptId}">
                                        <td class="labResultTemplateCell">
                                            <span class="labResultTemplateConcept" style="display:none;">${labConcept.conceptId}.${record.conceptId}</span>
                                        <openmrs_tag:obsValueField conceptId="${record.conceptId}" formFieldName="resultValue.${labConcept.conceptId}.${record.conceptId}" size="5" />

                                        </td>
                                    </openmrs:forEachRecord>
                                </c:when>
                                <c:otherwise>
                                    <td class="labResultTemplateCell">
                                        <span class="labResultTemplateConcept" style="display:none;">${labConcept.conceptId}.${labConcept.conceptId}</span>
                                    <openmrs_tag:obsValueField conceptId="${labConcept.conceptId}" formFieldName="resultValue.${labConcept.conceptId}.${labConcept.conceptId}" size="5" />
                                    </td>
                                </c:otherwise>
                            </c:choose>
                            </tr>
							<tr>
							<td colspan="3">
								<input type="checkbox" name="didTestFail_${labConcept.conceptId}.${labConcept.conceptId}" value="" onclick="javascript:scheduleOrder(this.checked)" id="didTestFail_${labConcept.conceptId}.${labConcept.conceptId}"/><strong>Reorder test</strong>
                            </td>
							</tr>
                        </table>
                    </div>
            </c:forEach>
            <br/>
            <div class="labResultDetailTemplate">
                <b style="padding-left:10px;">Date of Result:</b> 
				<input type="hidden" id="discontinuedDate" name="discontinuedDate" size="10" onFocus="showCalendar(this);"/>
				<input id="fakeDiscontinuedDate" type="text" size="10" value="${todayStr}" onFocus="showCalendar(this);" onChange="validateResultForm(this);"/>
				<span id="discontinuedDateError" style="color:red;"/>
            </div>			
			
            <div class="labFailureDetailTemplate" style="display:none;">
                <b style="padding-left:10px;">Reschedule Date:</b> <input type="text" name="rescheduleDate" size="10" onFocus="showCalendar(this)"/>
            </div>
        </div>
        <br/>
        <div align="center">
            <input type="button" id="saveOrderButton" name="SaveOrderButton" value="Save" onclick="saveThisOrder(this);" />
            <input type="button" value="Cancel" onclick="clearFormFields();" />
        </div>
        <br/>
    </div>
